package io.github.wppli.domain.pay.util;

import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * HTTP请求工具类
 */
@Component
public class HttpUtil {

    @Value("${personal.wxpay.mchid}")
    private String mch_id;

    @Value("${personal.wxpay.query-order-status-url}")
    private String queryOrderStatusUrl;

    @Value("${personal.wxpay.key}")
    private String personalKey;
    
    // 初始化配置（可选）
    static {
        Unirest.config()
                .connectTimeout(5000)
                .socketTimeout(10000)

        ;
    }

    /**
     * 发送POST表单请求
     * @param url 请求地址
     * @param headers 请求头（可为null）
     * @param formData 表单参数（格式：key1=value1&key2=value2）
     * @return 响应字符串
     * @throws RuntimeException 当请求失败时抛出
     */
    public String postForm(String url, Map<String, String> headers, String formData) {
        try {
            HttpResponse<String> response = Unirest.post(url)
                    .headers(headers)
                    .body(formData)
                    .asString();
            
            if (!response.isSuccess()) {
                throw new RuntimeException("请求失败，状态码：" + response.getStatus());
            }
            
            return response.getBody();
        } catch (Exception e) {
            throw new RuntimeException("HTTP请求异常: " + e.getMessage(), e);
        }
    }

    /**
     * 发送POST JSON请求
     * @param url 请求地址
     * @param headers 请求头（可为null）
     * @param jsonBody JSON字符串
     * @return 响应字符串
     */
    public String postJson(String url, Map<String, String> headers, String jsonBody) {
        try {
            HttpResponse<String> response = Unirest.post(url)
                    .headers(headers)
                    .header("Content-Type", "application/json")
                    .body(jsonBody)
                    .asString();
            
            if (!response.isSuccess()) {
                throw new RuntimeException("请求失败，状态码：" + response.getStatus());
            }
            
            return response.getBody();
        } catch (Exception e) {
            throw new RuntimeException("HTTP请求异常: " + e.getMessage(), e);
        }
    }


    public String queryOrderStatusRequest(String productId) {

        //当前时间戳
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);

        Map<String, Object> map = new HashMap<>();
        map.put("mch_id", mch_id);
        map.put("out_trade_no", productId);
        map.put("timestamp", timestamp);
        String sign = PaySignUtil.createSign(map, personalKey);

        String bodyData = String.format(
                "mch_id=%s&out_trade_no=%s&timestamp=%s&sign=%s",
                mch_id, productId, timestamp, sign);

        HttpResponse<String> response = Unirest.post(queryOrderStatusUrl)
                .header("content-type", "application/x-www-form-urlencoded")
                .body(bodyData)
                .asString();

        return response.getBody();
    }
}